#!/bin/bash

# Copyright (C) 2011 Karel Zak <kzak@redhat.com>
# This file is part of util-linux.

TS_TOPDIR="${0%/*}/../.."
TS_DESC="regular file"

. "$TS_TOPDIR"/functions.sh
ts_init "$*"

ts_check_test_command "$TS_CMD_MOUNT"
ts_check_test_command "$TS_CMD_UMOUNT"

ts_skip_nonroot
ts_check_losetup
ts_check_prog "mkfs.ext2"

IMAGE=$(ts_image_init)
mkfs.ext2 -F $IMAGE &> /dev/null || ts_die "Cannot make ext2 on $IMAGE"

[ -d "$TS_MOUNTPOINT" ] || mkdir -p $TS_MOUNTPOINT

$TS_CMD_MOUNT $IMAGE $TS_MOUNTPOINT >> $TS_OUTPUT 2>> $TS_ERRLOG

DEVICE=$(awk '/regfile/ { print $1 }' /proc/mounts)

ts_is_mounted "$TS_MOUNTPOINT" || ts_die "Cannot find $TS_MOUNTPOINT in /proc/mounts"

if [ -f "/sys/block/$(basename $DEVICE)/loop/backing_file" ]; then
	$TS_CMD_UMOUNT $IMAGE || ts_die "Cannot umount $IMAGE"
else
	$TS_CMD_UMOUNT $TS_MOUNTPOINT &> /dev/null
	ts_skip "too old kernel"
fi

ts_is_mounted "$TS_MOUNTPOINT" && ts_die "$TS_MOUNTPOINT still in /proc/mounts"

ts_log "Success"
ts_finalize

